package org.example.myleet.learn.bank;

import java.math.BigDecimal;

public class Bank {

    private int size;
    private BigDecimal[] accounts;

    public Bank() {
        size = 10;
        accounts = new BigDecimal[size];
        for (int i = 0; i < size; ++i) {
            accounts[i] = BigDecimal.valueOf(100);
        }
    }

    public int getSize() {
        return size;
    }

    public synchronized void transfer(long id, int from, int to, BigDecimal amount) {
        if (accounts[from].compareTo(amount) < 0) {
            try {
                wait(5000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (accounts[from].compareTo(amount) < 0) {
            System.out.println(id + "-account " + from + " is not enough to withdraw " + amount.toPlainString());
            return;
        }
        accounts[from] = accounts[from].subtract(amount);
        accounts[to] = accounts[to].add(amount);
        printState(id, from, to);
    }

    public void printState(long id, int from, int to) {
        StringBuilder sb = new StringBuilder();
        sb.append(id).append('-').append(from).append('-').append(to).append('-').append('[');
        BigDecimal total = BigDecimal.ZERO;
        for (int i = 0; i < size; ++i) {
            total = total.add(accounts[i]);
            if (i > 0) {
                sb.append(',');
            }
            sb.append(accounts[i].toPlainString());
        }
        sb.append(']');
        System.out.println(sb.toString() + ", total = " + total.toPlainString());
    }
}
